Trust Score
After successfully encrypting the 'Trust Score' data, the next essential task is to securely transmit it to our server. This involves creating an HTTP POST request, embedding the encrypted data within the request body, and utilizing your subscriptionKey for authentication.
Example HTTP POST Request in Various Languages
JavaScript
To execute a JavaScript file, it is advisable to install the Axios library, a popular choice for making HTTP requests in JavaScript environments.
Encryption Function
Create a file encryptionService.js, this file contains the encryption function.
const crypto = require('crypto');
function encryptData(data, pluginKeyHex) {
const pluginKey = Buffer.from(pluginKeyHex, 'hex');
if (pluginKey.length !== 32) {
throw new Error("Key must be 32 bytes for AES-256-CBC");
}
const iv = crypto.randomBytes(16);
const cipher = crypto.createCipheriv('aes-256-cbc', pluginKey, iv);
let encryptedData = cipher.update(JSON.stringify(data), 'utf8', 'base64');
encryptedData += cipher.final('base64');
const encryptedBlob = Buffer.concat([iv, Buffer.from(encryptedData, 'base64')]).toString('base64');
return encryptedBlob;
}
module.exports = {
encryptData
};
Sending encrypted data to the server
Create dataSender.js, This file contains the function to send encrypted data to the server.
const axios = require('axios');
function sendEncryptedData(encryptedData, apiUrl, subscriptionKey) {
const payload = {
queryData: encryptedData,
subscriptionKey: subscriptionKey
};
axios.post(apiUrl, payload, {
headers: {
'Content-Type': 'application/json'
}
}).then(response => {
console.log("Debug: API Response:", response.data);
}).catch(error => {
console.error("Error occurred:", error.response ? error.response.data : error.message);
});
}
module.exports = {
sendEncryptedData
};
Main code using both the function
Create App.js, this file uses both utilities to encrypt the data and send it.
const { encryptData } = require('./encryptionService');
const { sendEncryptedData } = require('./dataSender');
const testData = {
ogID: "your_og_id_here"
};
const pluginKeyHex = "your_encrypted_key_here"; // This should be the key in hex format
const subscriptionKey = "your_subscription_key_here";
const apiUrl = "your_api_url_here";
try {
console.log("Starting Encryption Process");
const encryptedResult = encryptData(testData, pluginKeyHex);
console.log("Sending Encrypted Data to API");
sendEncryptedData(encryptedResult, apiUrl, subscriptionKey);
} catch (e) {
console.error("An error occurred:", e.message);
}
Python
Installation Steps
- Ensure Python is Installed: Download and install the latest version of Python from the official Python website.
- Verify Python Installation: Run the command
python --version
to confirm that Python is installed correctly. - Check pip Installation: Verify the installation of pip, the package installer for Python, by executing
pip --version
. - Install the cryptography Package: Use pip to install the cryptography package required for cryptographic operations:
pip install cryptography
. - Confirm Installation: Ensure the cryptography package is installed successfully with the command
pip show cryptography
. - Install the requests Library: Install the requests library, commonly used for making HTTP requests in Python applications:
pip install requests
.
Encryption Function
Create a file encryption_service.py, this file contains the encryption function.
import json
import base64
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
import binascii
def encrypt_data(data, pluginkey):
method = 'AES-256-CBC'
iv_length = AES.block_size
iv = get_random_bytes(iv_length)
binary_key = binascii.unhexlify(pluginkey)
if len(binary_key) != 32:
raise ValueError("Key must be 32 bytes for AES-256-CBC")
cipher = AES.new(binary_key, AES.MODE_CBC, iv)
padded_data = data + (AES.block_size - len(data) % AES.block_size) * chr(AES.block_size - len(data) % AES.block_size)
encrypted_data = cipher.encrypt(padded_data.encode('utf-8'))
encrypted_data_with_iv = base64.b64encode(iv + encrypted_data).decode('utf-8')
return encrypted_data_with_iv
Sending encrypted data to the server
Create server_communication.py, This file contains the function to send encrypted data to the server.
import requests
def create_report_ghosting_page(encrypted_data, subscriptionKey, url):
payload = {
"queryData": encrypted_data,
"subscriptionKey": subscriptionKey
}
response = requests.post(url, json=payload)
if response.status_code == 200:
print("API Response:", response.json())
else:
print("Failed to send data. Status code:", response.status_code, "Response:", response.text)
Main code using both the function
Create main.py, this file uses both utilities to encrypt the data and send it.
import json
from encryption_service import encrypt_data
from server_communication import create_report_ghosting_page
if __name__ == "__main__":
pluginkey = "your_encrypted_key_here" # Replace with your actual encrypted key
subscriptionKey = "your_subscription_key_here" # Replace with your actual subscription key
api_url = "your_api_url_here" # Replace with your actual API URL
person = {
"email": "your_email_here" # Replace with your actual email
}
data_to_encrypt = json.dumps(person)
try:
encrypted_data = encrypt_data(data_to_encrypt, pluginkey)
create_report_ghosting_page(encrypted_data, subscriptionKey, api_url)
except Exception as e:
print(f"Operation failed: {e}")
C#
Setup Instructions for C# Development Environment
-
Install the "C#" Extension: Add the "C#" extension provided by Microsoft to your Visual Studio Code environment.
-
Install the C# Dev Kit: Incorporate the C# Dev Kit extension into Visual Studio Code to enhance your C# development capabilities.
-
Install the .NET Install Tool: Integrate the .NET Install Tool extension into Visual Studio Code for seamless management of .NET installations.
-
Download and Install .NET SDK: Obtain the .NET Software Development Kit (SDK) from the official .NET website and install it on your system.
-
Create a New C# File: Use the command
dotnet new console -n EncryptionApp
in your terminal to create a new C# file named "EncryptionApp" within your project directory. -
Add Newtonsoft.Json Package: Install the Newtonsoft.Json package, commonly used for JSON serialization and deserialization in C#, using the command
dotnet add package Newtonsoft.Json
.
Encryption Function
Create a class EncryptionService.cs, this class is responsible for data encryption.
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
public class EncryptionService
{
public static string EncryptData(string data, string pluginKey)
{
var binaryKey = StringToByteArray(pluginKey);
if (binaryKey.Length != 32)
throw new ArgumentException("Key must be 32 bytes for AES-256-CBC");
using (var aes = Aes.Create())
{
aes.Key = binaryKey;
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.PKCS7;
aes.GenerateIV();
var iv = aes.IV;
using (var encryptor = aes.CreateEncryptor(aes.Key, iv))
using (var ms = new MemoryStream())
{
ms.Write(iv, 0, iv.Length);
using (var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
using (var sw = new StreamWriter(cs))
{
sw.Write(data);
}
return Convert.ToBase64String(ms.ToArray());
}
}
}
private static byte[] StringToByteArray(string hex)
{
int NumberChars = hex.Length;
byte[] bytes = new byte[NumberChars / 2];
for (int i = 0; i < NumberChars; i += 2)
bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
return bytes;
}
}
Sending encrypted data to the server
Create a class named as DataCommunicationService.cs, class that handles all interactions with the server.
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
public class DataCommunicationService
{
private readonly string apiUrl;
public DataCommunicationService(string apiUrl)
{
this.apiUrl = apiUrl;
}
public async Task CreateReportGhostingPage(string encryptedData, string subscriptionKey)
{
using (var client = new HttpClient())
{
var payload = new
{
queryData = encryptedData,
subscriptionKey = subscriptionKey
};
var content = new StringContent(JsonConvert.SerializeObject(payload), Encoding.UTF8, "application/json");
var response = await client.PostAsync(apiUrl, content);
var responseString = await response.Content.ReadAsStringAsync();
Console.WriteLine("API Response: " + responseString);
}
}
}
Main code using both the function
Create Program.cs, this file uses both utilities to encrypt the data and send it.
using System;
public class Program
{
private static readonly string pluginKey = "your_encrypted_key_here"; // Replace with your actual encrypted key
private static readonly string subscriptionKey = "your_subscription_key_here"; // Replace with your actual subscription key
private static readonly string apiUrl = "your_api_url_here"; // Replace with your actual API URL
public static void Main(string[] args)
{
var person = new { email = "your_email_here" }; // Replace with your actual email
var dataToEncrypt = JsonConvert.SerializeObject(person);
try
{
var encryptedData = EncryptionService.EncryptData(dataToEncrypt, pluginKey);
var communicator = new DataCommunicationService(apiUrl);
communicator.CreateReportGhostingPage(encryptedData, subscriptionKey).Wait();
}
catch (Exception ex)
{
Console.WriteLine($"Operation failed: {ex.Message}");
}
}
}
PHP
Running the Provided PHP Code
To execute the provided PHP code successfully, follow these steps:
- Open the
php.ini
file:- This file is typically located in
xampp/php/php.ini
on Windows orApplications/XAMPP/xamppfiles/etc/php.ini
on macOS.
- This file is typically located in
- Find and enable the OpenSSL extension:
- Search for the line
;extension=openssl
. - Remove the semicolon (
;
) at the beginning of the line to uncomment and thus enable it.
- Search for the line
- Enable the cURL extension:
- Find the line
;extension=curl
. - Similarly, remove the semicolon to enable the extension.
- Find the line
- Save the changes to the
php.ini
file.
Encryption Function
Create a file EncryptionService.php, this file is responsible for data encryption.
class EncryptionService
{
public static function encryptData($data, $pluginKey) {
$method = 'AES-256-CBC';
$ivLength = openssl_cipher_iv_length($method);
$iv = openssl_random_pseudo_bytes($ivLength);
$binaryKey = hex2bin($pluginKey);
if (strlen($binaryKey) !== 32) {
throw new Exception("Key must be 32 bytes for AES-256-CBC");
}
$paddedData = $data . str_repeat(chr($ivLength - strlen($data) % $ivLength), $ivLength - strlen($data) % $ivLength);
$encryptedData = openssl_encrypt($paddedData, $method, $binaryKey, OPENSSL_RAW_DATA, $iv);
$encryptedDataWithIv = base64_encode($iv . $encryptedData);
return $encryptedDataWithIv;
}
}
Sending encrypted data to the server
Create a file named ServerCommunicationService.php to handle communication with the server.
class ServerCommunicationService
{
public static function createReportGhostingPage($encryptedData, $subscriptionKey, $apiUrl) {
$payload = [
'queryData' => $encryptedData,
'subscriptionKey' => $subscriptionKey
];
$ch = curl_init($apiUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
$response = curl_exec($ch);
if (curl_errno($ch)) {
throw new Exception(curl_error($ch));
}
curl_close($ch);
return $response;
}
}
Main code using both the function
Create a main file as index.php that uses the EncryptionService and ServerCommunicationService for its operations.
require_once 'EncryptionService.php';
require_once 'ServerCommunicationService.php';
// Replace with your actual keys and API URL
$pluginKey = 'your_encrypted_key_here';
$subscriptionKey = 'your_subscription_key_here';
$apiUrl = 'your_api_url_here';
// Replace with your actual data
$person = [
'email' => 'your_email_here'
];
$dataToEncrypt = json_encode($person);
try {
$encryptedData = EncryptionService::encryptData($dataToEncrypt, $pluginKey);
$response = ServerCommunicationService::createReportGhostingPage($encryptedData, $subscriptionKey, $apiUrl);
echo "API Response: " . $response . PHP_EOL;
} catch (Exception $e) {
echo "Encryption failed: " . $e->getMessage() . PHP_EOL;
}
JAVA
Adding Dependencies for Running Java Code
To run the provided Java code successfully, you need to include the following dependencies in your project:
-
Gson:
-
Gson is a Java library used for JSON serialization and deserialization.
-
Add the Gson dependency to your project by including the following Maven or Gradle configuration:
<!-- Maven -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.8</version>
</dependency>// Gradle
implementation 'com.google.code.gson:gson:2.8.8'
-
-
Apache HttpClient:
-
Apache HttpClient is a library used for making HTTP requests in Java.
-
Include the Apache HttpClient dependency in your project with the following Maven or Gradle configuration:
<!-- Maven -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>// Gradle
implementation 'org.apache.httpcomponents:httpclient:4.5.13'
-
-
Bouncy Castle Provider:
-
Bouncy Castle is a cryptography library that provides algorithms and utilities for encryption and decryption.
-
Add the Bouncy Castle Provider dependency to your project using the following Maven or Gradle configuration:
<!-- Maven -->
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.68</version>
</dependency>// Gradle
implementation 'org.bouncycastle:bcprov-jdk15on:1.68'
-
Once you've added these dependencies to your project configuration, your Java project will have access to the required packages for running the provided code.
Encryption Function
Create an EncryptionService Class, this class will handle all the encryption processes.
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.security.SecureRandom;
import java.util.Base64;
import java.nio.charset.StandardCharsets;
public class EncryptionService {
public static String encryptData(String data, String pluginKeyHex) throws Exception {
byte[] pluginKey = hexStringToByteArray(pluginKeyHex);
if (pluginKey.length != 32) {
throw new IllegalArgumentException("Key must be 32 bytes for AES-256-CBC");
}
byte[] iv = new byte[16];
new SecureRandom().nextBytes(iv);
SecretKeySpec secretKeySpec = new SecretKeySpec(pluginKey, "AES");
IvParameterSpec ivSpec = new IvParameterSpec(iv);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivSpec);
byte[] encryptedData = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
byte[] encryptedDataWithIv = new byte[iv.length + encryptedData.length];
System.arraycopy(iv, 0, encryptedDataWithIv, 0, iv.length);
System.arraycopy(encryptedData, 0, encryptedDataWithIv, iv.length, encryptedData.length);
return Base64.getEncoder().encodeToString(encryptedDataWithIv);
}
private static byte[] hexStringToByteArray(String s) {
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
+ Character.digit(s.charAt(i + 1), 16));
}
return data;
}
}
Sending encrypted data to the server
Create a ServerCommunicationService Class, this class will handle all HTTP communication with the server.
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.URI;
public class ServerCommunicationService {
public static void sendEncryptedData(String encryptedData, String apiUrl, String subscriptionKey) throws Exception {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI(apiUrl))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(
String.format("{\"queryData\":\"%s\", \"subscriptionKey\":\"%s\"}", encryptedData, subscriptionKey)))
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println("Debug: API Response: " + response.body());
}
}
Main code using both the function
Create a Main Class, this class will now use the EncryptionService and ServerCommunicationService to perform tasks.
public class Main {
public static void main(String[] args) {
String testData = "{\"ogID\":\"your_og_id_here\"}";
String pluginKey = "your_encrypted_key_here";
String subscriptionKey = "your_subscription_key_here";
String apiUrl = "your_api_url_here";
try {
System.out.println("Starting Encryption Process");
String encryptedResult = EncryptionService.encryptData(testData, pluginKey);
System.out.println("Sending Encrypted Data to API");
ServerCommunicationService.sendEncryptedData(encryptedResult, apiUrl, subscriptionKey);
} catch (Exception e) {
System.err.println("An error occurred: " + e.getMessage());
e.printStackTrace();
}
}
}
GO
Setting up Go Development Environment
To begin developing with Go programming language, follow these steps:
-
Install Go Programming Language:
- Download and install the Go programming language from the official website: golang.org.
-
Install Go Extension in Visual Studio Code:
- Open Visual Studio Code.
- Navigate to the Extensions view by clicking on the square icon on the sidebar or pressing
Ctrl+Shift+X
. - Search for "Go" in the Extensions Marketplace.
- Click on the "Install" button next to the "Go" extension provided by Go Team at Google.
These steps will ensure that you have the necessary tools and extensions to start developing with Go in Visual Studio Code.
Encryption Function
Create an Encryption Package called as encryption.go, this package handles all encryption-related tasks.
package encryption
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"encoding/hex"
"encoding/json"
"fmt"
"io"
)
type TestData struct {
OgID string `json:"ogID"`
}
func EncryptData(data TestData, pluginKeyHex string) (string, error) {
pluginKey, err := hex.DecodeString(pluginKeyHex)
if err != nil {
return "", err
}
if len(pluginKey) != 32 {
return "", fmt.Errorf("key must be 32 bytes for AES-256-CBC")
}
iv := make([]byte, aes.BlockSize)
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
return "", err
}
block, err := aes.NewCipher(pluginKey)
if err != nil {
return "", err
}
plainText, err := json.Marshal(data)
if err != nil {
return "", err
}
paddedText := pkcs7Pad(plainText, aes.BlockSize)
cipherText := make([]byte, len(paddedText))
mode := cipher.NewCBCEncrypter(block, iv)
mode.CryptBlocks(cipherText, paddedText)
encryptedBlob := append(iv, cipherText...)
return base64.StdEncoding.EncodeToString(encryptedBlob), nil
}
func pkcs7Pad(data []byte, blockSize int) []byte {
padding := blockSize - len(data)%blockSize
padText := bytes.Repeat([]byte{byte(padding)}, padding)
return append(data, padText...)
}
Sending encrypted data to the server
Create a package as communication.go, this package will be responsible for sending encrypted data to the server.
package communication
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
)
type Payload struct {
QueryData string `json:"queryData"`
SubscriptionKey string `json:"subscriptionKey"`
}
func SendEncryptedData(encryptedData, apiUrl, subscriptionKey string) error {
payload := Payload{
QueryData: encryptedData,
SubscriptionKey: subscriptionKey,
}
payloadBytes, err := json.Marshal(payload)
if err != nil {
return err
}
resp, err := http.Post(apiUrl, "application/json", bytes.NewReader(payloadBytes))
if err != nil {
return err
}
defer resp.Body.Close()
var result map[string]interface{}
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return err
}
fmt.Println("Debug: API Response:", result)
return nil
}
Main code using both the function
Create a main package as Main.go, this is the main entry point of your application.
package main
import (
"fmt"
"yourproject/encryption"
"yourproject/communication"
)
func main() {
testData := encryption.TestData{OgID: "your_og_id_here"}
pluginKeyHex := "your_encrypted_key_here"
subscriptionKey := "your_subscription_key_here"
apiUrl := "your_api_url_here"
fmt.Println("Starting Encryption Process")
encryptedResult, err := encryption.EncryptData(testData, pluginKeyHex)
if err != nil {
fmt.Println("An error occurred during encryption:", err)
return
}
fmt.Println("Sending Encrypted Data to API")
if err := communication.SendEncryptedData(encryptedResult, apiUrl, subscriptionKey); err != nil {
fmt.Println("An error occurred while sending data:", err)
}
}